package com.arch.dev.server;

import java.io.File;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;


import com.arch.dev.client.PdfService;
import com.arch.dev.client.vo.BudgetVO;
import com.arch.dev.client.vo.PdfVO;
import com.arch.dev.server.pdf.FirstPdf;
import com.arch.dev.server.report.PdfJasperReport;
import com.arch.dev.server.report.ReportFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class PdfServiceImpl extends RemoteServiceServlet implements PdfService {
	
	Logger logger = Logger.getLogger(PdfServiceImpl.class);	

	ReportFactory pdfJasperReport = new PdfJasperReport();

	private static final long serialVersionUID = 8046131782182865206L;

	public void deletePDF(Set<PdfVO> pdfVOs) throws Exception {
		ServletContext sc = this.getServletContext();
		File directory = new File(sc.getRealPath("/") + "PDF");
		for (PdfVO pdfVO : pdfVOs) {
			String pdfName = pdfVO.getName();

			File file = new File(directory, pdfName + ".pdf");

			if (file.exists()) {

				if (file.delete()) {
					logger.info("File is deleted :"
							+ file.getAbsolutePath());
				}

			}

		}

	}

	public PdfVO generatePDF(List<BudgetVO> budgetVOs) throws Exception {

		FirstPdf firstPDF = new FirstPdf();

		Calendar cl = Calendar.getInstance();

		Date date = cl.getTime();

		Long time = cl.getTimeInMillis();

		String pdfName = "MONTHLY_PDF_" + time;

		ServletContext sc = this.getServletContext();

		logger.info("*********" + sc.getRealPath("/"));

		File directory = new File(sc.getRealPath("/") + "PDF");

		if (!directory.exists()) {

			directory.mkdir();

		}

		File file = new File(directory, pdfName + ".pdf");

		logger.info("*****" + file.getAbsolutePath());

		String relativeWebPath = "/images/MoneyExpenditure.jpg";

		String absoluteDiskPath = getServletContext().getRealPath(
				relativeWebPath);

		Collections.sort(budgetVOs, new Comparator <BudgetVO>(){

			@Override
			public int compare(BudgetVO o1, BudgetVO o2) {
				// TODO Auto-generated method stub
				return o1.getDate().compareTo(o2.getDate());
			}
			
		});
		
		// firstPDF.generatePDF(file, absoluteDiskPath, budgetVOs);

		pdfJasperReport.getReport(budgetVOs, file.getAbsolutePath(),
				sc.getRealPath("/"));

		PdfVO pdfVO = new PdfVO();

		pdfVO.setDate(date);

		pdfVO.setName(pdfName);

		return pdfVO;

	}
	
	

}